using System.Collections.Generic;
using System.Linq;

namespace Flood.FloodStrategies
{
	/// <summary>
	/// moves on the sample set
	/// 24172 in 3.191
	/// </summary>
	public sealed class FloodAdjacentColorThatHasTheMostDrySquaresPreferMoreBorderSquares : FloodStrategyBase, IFloodStrategy
	{
		#region IFloodStrategy Members

		public Result GetNextToFlood(IEnumerable<Shape> moistShapes, Grid grid)
		{
			var dryAdjacent = moistShapes
				.Select(shape => new { shape.DryAdjacentShapes, Shape = shape });

			var dryAdjacentWithCounts = dryAdjacent
				.Select(item => new
				                	{
				                		SquareCount = item.DryAdjacentShapes.Sum(shape => shape.Parts.Count),
				                		BorderCount = item.DryAdjacentShapes.Select(shape => shape.Color).Distinct().Count(),
				                		item.Shape
				                	})
				.OrderByDescending(item => item.BorderCount);
			var first = dryAdjacentWithCounts.First();
			if (first.SquareCount == 0)
			{
				// there are no more blocked squares so the solution
				// order for the remaining squares doesn't matter
				return new Result(moistShapes.Select(shape => shape.Color).OrderByDescending(x => x).ToList(), true);
			}

			var thoseWithHighestCount =
				dryAdjacentWithCounts.Where(item => item.SquareCount + item.BorderCount == first.SquareCount + first.BorderCount)
					.OrderByDescending(item => item.BorderCount);

			char bestColor = thoseWithHighestCount.First().Shape.Color;

			return new Result(bestColor, false);
		}

		#endregion
	}
}